package com.imooc.coupon.service.impl;

import com.imooc.coupon.exception.CouponException;
import com.imooc.coupon.service.AsyncService;
import com.imooc.coupon.service.BuildTemplateService;
import com.imooc.coupon.support.vo.TemplateRequest;
import com.imooc.coupon.entity.CouponTemplate;
import com.imooc.coupon.repository.CouponTemplateRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 构建优惠券模板接口实现
 * Created By TINY
 * Create Time 2020/2/10
 **/
@Slf4j
@Service
public class BuildTemplateServiceImpl implements BuildTemplateService {

    /** 异步服务 */
    private final AsyncService asyncService;

    /** CouponTemplate持久层 */
    private final CouponTemplateRepo templateRepo;

    @Autowired
    public BuildTemplateServiceImpl(
            AsyncService asyncService, CouponTemplateRepo templateRepo) {
        this.asyncService = asyncService;
        this.templateRepo = templateRepo;
    }

    /**
     * 创建优惠券模板
     *
     * @param request {@link TemplateRequest} 模板创建请求对象
     * @return {@link CouponTemplate} 优惠券模板实体
     * @throws CouponException 业务异常
     */
    @Override
    public CouponTemplate buildTemplate(TemplateRequest request)
            throws CouponException {

        // 参数合法性校验
        if (!request.validate()) {
            throw new CouponException("BuildTemplate 参数异常！");
        }

        // 如果数据库中存在同名的优惠券模板，则抛出异常
        if (null != templateRepo.findByName(request.getName())) {
            throw new CouponException("优惠券已存在！");
        }

        // 构造 CouponTemplate 并保存到数据库中
        CouponTemplate couponTemplate = request2Template(request);
        couponTemplate = templateRepo.save(couponTemplate);

        // 根据优惠券模板异步生成优惠券码
        asyncService.asyncConstructCouponByTemplate(couponTemplate);

        return couponTemplate;
    }

    /**
     * 将 TemplateRequest 对象转换为 CouponTemplate
     * @param request {@link TemplateRequest} 模板创建请求对象
     * @return {@link CouponTemplate}优惠券模板实体
     */
    private CouponTemplate request2Template(TemplateRequest request) {
        return new CouponTemplate(
                request.getName(),
                request.getLogo(),
                request.getDesc(),
                request.getCategory(),
                request.getProductLine(),
                request.getCount(),
                request.getUserId(),
                request.getTarget(),
                request.getRule()
        );
    }
}
